import { useState, useCallback, useEffect, cloneElement } from 'react'
import { View } from 'react-native'

const BaseSuspense = ({ style, children, loading, error, empty, onFetch }) => {
  const [state, setState] = useState(null)
  const [tips, setTips] = useState('')

  const doFetch = useCallback(async () => {
    try {
      setState('loading')
      await onFetch?.()
      setState('done')
    } catch (e) {
      console.log(e)
      if (e.noContent) {
        setState('empty')
        e.message !== '成功' && setTips(e.message)
      } else {
        setState('error')
      }
    }
  }, [onFetch])

  useEffect(() => {
    doFetch()
  }, [doFetch])

  return (
    <View style={style}>
      {state === 'loading' && loading}
      {state === 'error' && cloneElement(error, { onReload: doFetch })}
      {state === 'empty' && cloneElement(empty, { tips })}
      {state === 'done' && children}
    </View>
  )
}

export default BaseSuspense
